package com.yenlien.traceyun.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-03-10
 * @description:
 **/
public class LoggerUtil {

    private static Logger logger = LoggerFactory.getLogger("traceyun");

    public static Logger getLogger() {
        return logger;
    }

    public static void logError(String msg, Throwable throwable) {
        logger.error(msg);
        log(throwable);
    }

    public static void logError(String msg) {
        logger.error(msg);
    }

    public static void logInfo(String msg) {
        logger.info(msg);
    }

    private static void log(Throwable throwable) {
        if (throwable != null) {
            int length = throwable.getStackTrace().length;
            if (length > 0) {
                StackTraceElement element = throwable.getStackTrace()[0];
                String exceptionInfo = null;
                if (element == null)
                    return;
                exceptionInfo = "class=" + element.getClassName() + ",method=" + element.getMethodName() + ",file="
                        + element.getFileName() + ",line=" + element.getLineNumber();
                LoggerUtil.getLogger().error("error begin,exception:{},msg:{}", exceptionInfo, throwable.getMessage());
                for (int i = 1; i < length; i++) {
                    StackTraceElement item = throwable.getStackTrace()[i];
                    String classname = item.getClassName();
                    if (classname.startsWith("com.yenlien.traceyun")) {
                        exceptionInfo = "class=" + item.getClassName() + ",method=" + item.getMethodName() + ",file="
                                + item.getFileName() + ",line=" + item.getLineNumber();
                        LoggerUtil.getLogger().error("error trace ,exception:{}", exceptionInfo);
                    }
                }

            }
        }
    }

}
